package com.example.myapplication.ui

import android.Manifest
import android.app.WallpaperManager
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.graphics.createBitmap
import androidx.core.graphics.scale
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.disk.DiskCache
import coil.imageLoader
import coil.memory.MemoryCache
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.example.myapplication.bing.BingWallpaper
import com.example.myapplication.bing.WallpaperInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

// 裁剪图片模式
enum class CropGravity { CENTER, TOP, BOTTOM, LEFT, RIGHT }

@Composable
fun ImageViewerScreen() {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    // 使用 remember 和 mutableStateOf 管理状态
    var wallpaper by remember { mutableStateOf<WallpaperInfo?>(null) }
    var loading by remember { mutableStateOf(true) }
    var descriptionExpanded by remember { mutableStateOf(false) }
    // 全屏预览
    var fullscreenPreview by remember { mutableStateOf(false) }
    // 图片加载
    var imageLoading by remember { mutableStateOf(true) }

    val first by remember { mutableStateOf(true) }
    // 保存图片权限（Android 13+ 用 READ_MEDIA_IMAGES，否则用 WRITE_EXTERNAL_STORAGE）
    val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        Manifest.permission.READ_MEDIA_IMAGES
    else
        Manifest.permission.WRITE_EXTERNAL_STORAGE

    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (!granted) {
            Toast.makeText(context, "没有保存权限", Toast.LENGTH_SHORT).show()
        } else {
            wallpaper?.let { wallpaperInfo ->
                // 权限获取成功后才执行保存操作
                coroutineScope.launch {
                    saveImageAndShowToast(context, wallpaperInfo.portraitImageUrl)
                }
            }
        }
    }

    val imageLoader = remember(context) {
        ImageLoader.Builder(context)
            .diskCachePolicy(CachePolicy.ENABLED)
            .memoryCachePolicy(CachePolicy.ENABLED)
            .memoryCache {
                MemoryCache.Builder(context)
                    .maxSizePercent(0.15)
                    .build()
            }
            .diskCache(
                DiskCache.Builder()
                    .directory(context.cacheDir.resolve("image_cache"))
                    .maxSizeBytes(10 * 1024 * 1024) // 10MB 缓存
                    .build()
            )
            .build()
    }
    @OptIn(coil.annotation.ExperimentalCoilApi::class)
    val clearImageCache = {
        // 清理缓存
        imageLoader.memoryCache?.clear()
        imageLoader.diskCache?.clear()
    }

    // 在后台线程加载壁纸信息
    LaunchedEffect(Unit) {
        try {
            val bingWallpaper = BingWallpaper()
            val wallpaperInfo = withContext(Dispatchers.IO) {
                bingWallpaper.getDailyWallpaperInfo()
            }
            wallpaper = wallpaperInfo
        } catch (e: Exception) {
            e.printStackTrace()
            // 处理错误情况，可以设置默认壁纸或显示错误信息
        } finally {
            if ( first){
                // 等1秒
                delay(1000)
            }
            loading = false
        }
    }

    // 在组件销毁时清理缓存
    DisposableEffect(Unit) {
        onDispose {
            clearImageCache()
        }
    }

    // Scaffold布局
    Log.e("BingWallpaper", wallpaper.toString())
    Scaffold(
        contentWindowInsets = WindowInsets(0),
        content = { paddingValues ->
            Surface(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                color = MaterialTheme.colorScheme.background
            ) {
                if (loading) {
                    LoadingScreen()
                } else {
                    wallpaper?.let { wallpaperInfo ->
                        if (fullscreenPreview) {
                            // 全屏预览模式
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
//                                    .statusBarsPadding()
                                    .background(Color.Black)
                            ) {
                                AsyncImage(
                                    model = ImageRequest.Builder(context)
                                        .data(wallpaperInfo.portraitImageUrl)
                                        .crossfade(true)
                                        .diskCachePolicy(CachePolicy.ENABLED)
                                        .memoryCachePolicy(CachePolicy.ENABLED)
                                        .size(1440, 2560) // 根据设备屏幕调整尺寸
                                        .allowHardware(true)
                                        .build(),
                                    contentDescription = "全屏预览图片",
                                    placeholder = ColorPainter(Color.LightGray),
                                    error = ColorPainter(Color.Red),
                                    contentScale = ContentScale.Fit,
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .fillMaxWidth()
                                        .clickable(
                                            interactionSource = remember { MutableInteractionSource() },
                                            indication = null
                                        ) {
                                            fullscreenPreview = false
                                        },
                                    imageLoader = imageLoader
                                )

                                // 关闭按钮
                                IconButton(
                                    onClick = { fullscreenPreview = false },
                                    modifier = Modifier
                                        .align(Alignment.TopEnd)
                                        .padding(16.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Close,
                                        contentDescription = "关闭全屏预览",
                                        tint = Color.White.copy(alpha = 0.8f)
                                    )
                                }
                            }
                        } else {
                            Column(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(paddingValues)
                                    .padding(12.dp)
                                    .verticalScroll(rememberScrollState())
                            ) {
                                // 图片标题
                                Surface(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 4.dp),
                                    shape = RoundedCornerShape(6.dp),
                                    color = MaterialTheme.colorScheme.primaryContainer,
                                    shadowElevation = 2.dp
                                ) {
                                    Text(
                                        text = wallpaperInfo.title,
                                        style = MaterialTheme.typography.bodyLarge,
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 8.dp, horizontal = 10.dp),
                                        color = MaterialTheme.colorScheme.onPrimaryContainer,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                        textAlign = TextAlign.Center
                                    )
                                }

                                // 图片展示区域 - 使用卡片样式
                                Surface(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .aspectRatio(9f / 16f)
                                        .padding(vertical = 2.dp)
                                        .clickable {
                                            imageLoading = true // 点击进入全屏预览时重置加载状态
                                            fullscreenPreview = true
                                        },
                                    shape = RoundedCornerShape(6.dp),
                                    shadowElevation = 4.dp,
                                    color = MaterialTheme.colorScheme.surface
                                ) {
                                    Box(
                                        modifier = Modifier.fillMaxSize(),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        AsyncImage(
                                            model = ImageRequest.Builder(context)
                                                .data(wallpaperInfo.portraitImageUrl)
                                                .crossfade(true)
                                                .diskCachePolicy(CachePolicy.ENABLED)
                                                .memoryCachePolicy(CachePolicy.ENABLED)
                                                .size(1080, 1920) // 限制图像尺寸，避免加载过大的图像
                                                .allowHardware(true) // 允许硬件位图加速
                                                .build(),
                                            contentDescription = "图片",
                                            placeholder = ColorPainter(Color.LightGray),
                                            error = ColorPainter(Color.Red),
                                            contentScale = ContentScale.Fit,
                                            modifier = Modifier.fillMaxSize(),
                                            onSuccess = {
                                                Log.i("ImageViewerScreen", "Image loaded successfully")
                                                imageLoading = false
                                            },
                                            onError = {
                                                imageLoading = false
                                            },
                                            imageLoader = imageLoader
                                        )

                                        // 图片加载进度条
                                        if (imageLoading) {
                                            Column(
                                                horizontalAlignment = Alignment.CenterHorizontally,
                                                modifier = Modifier.padding(16.dp)
                                            ) {
                                                CircularProgressIndicator(
                                                    modifier = Modifier.padding(8.dp)
                                                )
                                                Text(
                                                    text = "图片加载中...",
                                                    style = MaterialTheme.typography.bodySmall,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                        }
                                    }
                                }
                                // 图片描述区域 - 使用卡片样式
                                Surface(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 8.dp, bottom = 8.dp),
                                    shape = RoundedCornerShape(12.dp),
                                    shadowElevation = 2.dp,
                                    color = MaterialTheme.colorScheme.surface
                                ) {
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp)
                                    ) {
                                        Text(
                                            text = wallpaperInfo.description,
                                            style = MaterialTheme.typography.bodyMedium,
                                            softWrap = true,
                                            maxLines = if (descriptionExpanded) Int.MAX_VALUE else 3,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .clickable { descriptionExpanded = !descriptionExpanded },
                                            overflow = TextOverflow.Ellipsis,
                                        )

                                        // 展开/收起按钮
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 12.dp)
                                                .clickable { descriptionExpanded = !descriptionExpanded },
                                            horizontalArrangement = Arrangement.Center,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 添加旋转动画的图标
                                            val rotationAngle by animateFloatAsState(
                                                targetValue = if (descriptionExpanded) 180f else 0f,
                                                animationSpec = tween(durationMillis = 300),
                                                label = "rotation"
                                            )

                                            Icon(
                                                imageVector = if (descriptionExpanded) Icons.Default.KeyboardArrowUp
                                                else Icons.Default.KeyboardArrowDown,
                                                contentDescription = if (descriptionExpanded) "收起" else "展开",
                                                modifier = Modifier
                                                    .rotate(rotationAngle),
                                                tint = MaterialTheme.colorScheme.primary
                                            )

                                            Text(
                                                text = if (descriptionExpanded) "收起" else "展开",
                                                style = MaterialTheme.typography.bodySmall,
                                                color = MaterialTheme.colorScheme.primary,
                                                modifier = Modifier.padding(start = 4.dp)
                                            )
                                        }
                                    }
                                }

                                // 底部按钮区域1
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 16.dp),
                                    horizontalArrangement = Arrangement.SpaceEvenly
                                ) {
                                    Button(
                                        onClick = {
                                            // 重新加载壁纸
                                            loading = true
                                            coroutineScope.launch {
                                                try {
                                                    val bingWallpaper = BingWallpaper()
                                                    val newWallpaper = withContext(Dispatchers.IO) {
                                                        bingWallpaper.getDailyWallpaperInfo()
                                                    }
                                                    wallpaper = newWallpaper
                                                } catch (e: Exception) {
                                                    e.printStackTrace()
                                                    // 可以添加错误提示
                                                    withContext(Dispatchers.Main) {
                                                        Toast.makeText(
                                                            context,
                                                            "加载失败，请重试",
                                                            Toast.LENGTH_SHORT
                                                        ).show()
                                                    }
                                                } finally {
                                                    loading = false
                                                    imageLoading = true
                                                    clearImageCache()
                                                }
                                            }
                                        },
                                        modifier = Modifier
                                            .weight(1f)
                                            .padding(end = 8.dp)
                                    ) {
                                        Text("换一个")
                                    }

                                    Button(
                                        onClick = {
                                            // 请求权限并保存图片
                                            permissionLauncher.launch(permission)
                                        },
                                        modifier = Modifier
                                            .weight(1f)
                                            .padding(start = 8.dp)
                                    ) {
                                        Text("保存图片")
                                    }

                                }

                                // 底部按钮区域2
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(bottom = 24.dp),
                                    horizontalArrangement = Arrangement.SpaceEvenly
                                ){
                                    // 设置壁纸
                                    Button(
                                        onClick = {
                                            // 设置手机壁纸
                                            coroutineScope.launch {
                                                wallpaper?.landscapeImageUrl?.let { setWallpaper(context, it,WallpaperManager.FLAG_SYSTEM) }
                                            }
                                        },
                                        modifier = Modifier
                                            .weight(1f)
                                            .padding(end = 8.dp)
                                    ){
                                        Text("设置手机壁纸")
                                    }

                                Button(
                                    onClick = {
                                        // 设置手机锁屏壁纸
                                        coroutineScope.launch {
                                            wallpaper?.landscapeImageUrl?.let { setWallpaper(context, it,WallpaperManager.FLAG_LOCK) }
                                        }
                                    },
                                    modifier = Modifier
                                        .weight(1f)
                                        .padding(start = 8.dp)
                                ){
                                    Text("设置锁屏")
                                }
                            }
                            }

                        }
                    } ?: run {
                        // 处理壁纸为空的情况
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(paddingValues),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "壁纸加载失败",
                                    style = MaterialTheme.typography.headlineSmall,
                                    modifier = Modifier.padding(bottom = 16.dp)
                                )
                                Button(
                                    onClick = {
                                        // 重新尝试加载
                                        loading = true
                                        coroutineScope.launch {
                                            try {
                                                val bingWallpaper = BingWallpaper()
                                                val wallpaperInfo = withContext(Dispatchers.IO) {
                                                    bingWallpaper.getDailyWallpaperInfo()
                                                }
                                                wallpaper = wallpaperInfo
                                            } catch (e: Exception) {
                                                e.printStackTrace()
                                            } finally {
                                                loading = false
                                            }
                                        }
                                    }
                                ) {
                                    Text("重新加载")
                                }
                            }
                        }
                    }
                }
            }
        }
    )
}
suspend fun saveImageAndShowToast(context: Context, url: String) {
    val result = try {
        // 1. 使用 Coil 获取图片数据（自动处理缓存）
        val imageLoader = context.imageLoader
        val request = ImageRequest.Builder(context)
            .data(url)
            .allowHardware(false) // 确保可以获取 Bitmap
            .build()

        val drawable = imageLoader.execute(request).drawable
        val bitmap = (drawable as? BitmapDrawable)?.bitmap!!
        // 2. 保存到相册
        saveBitmapToGallery(context, bitmap, getFileNameFromUrl(url))
        true
        } catch (e: Exception) {
        e.printStackTrace()
        false
    }

    // 3. 显示 Toast
    withContext(Dispatchers.Main) {
        val message = if (result) "图片已保存到相册" else "保存失败"
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
}

/** 从 URL 提取文件名（如 "https://example.com/image.jpg" → "image.jpg"） */
private fun getFileNameFromUrl(url: String): String {
    return url.substringAfterLast('/').takeIf { it.isNotBlank() }
        ?: "image_${System.currentTimeMillis()}.jpg"
}

/** 保存 Bitmap 到相册 */
private fun saveBitmapToGallery(context: Context, bitmap: Bitmap, fileName: String): Boolean {
    return try {
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }
        }

        val resolver = context.contentResolver
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            ?: return false

        resolver.openOutputStream(uri)?.use { outputStream ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.clear()
            contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
            resolver.update(uri, contentValues, null, null)
        }
        true
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}


// 在文件末尾添加 LoadingScreen 组件：
@Composable
fun LoadingScreen() {
    // 创建无限循环的动画
    val infiniteTransition = rememberInfiniteTransition(label = "loading")
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = LinearEasing)
        ), label = "rotation"
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Icon(
                imageVector = Icons.Default.Star, // 可以替换为其他图标
                contentDescription = null,
                modifier = Modifier
                    .size(48.dp)
                    .rotate(rotation),
                tint = MaterialTheme.colorScheme.primary
            )
            Text(
                text = "正在加载中...",
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(top = 16.dp)
            )

        }
        // 最底下显示作者信息
        Text(
            text = "Powered By AlanNiew",
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(top = 16.dp)
                .padding(bottom = 24.dp)
        )
    }
}

suspend fun setWallpaper(context: Context, url: String, flag: Int) {
    try {
        // 1) 获取锁屏屏幕实际像素尺寸
        val (screenWidth, screenHeight) = getScreenSizePx(context)

        // 2) 用 Coil 解码，尽量按目标尺寸获取（避免超大图内存/缩放误差）
        val imageLoader = context.imageLoader
        val request = ImageRequest.Builder(context)
            .data(url)
            .allowHardware(false)
            .size(screenWidth, screenHeight) // 让解码贴近目标尺寸
            .scale(coil.size.Scale.FILL)     // 使用FILL模式来获取更大图像
            .build()
        val drawable = imageLoader.execute(request).drawable
        val srcBitmap = (drawable as? BitmapDrawable)?.bitmap
            ?: error("Decode bitmap failed")
        val wm = WallpaperManager.getInstance(context)

        var message = "设置壁纸成功"
        if (flag == WallpaperManager.FLAG_SYSTEM){
            wm.setBitmap(srcBitmap, Rect(0, 0, screenWidth, screenHeight), false, flag)
        }else{
            // 3) 生成与屏幕同尺寸的位图：等比放大 + 居中 + 留白
            val fitBitmap = createCropFillBitmap(srcBitmap, screenWidth, screenHeight)
            // 4) 设置锁屏或系统壁纸（无裁剪）
            wm.setBitmap(fitBitmap, Rect(0, 0, fitBitmap.width, fitBitmap.height), false, flag)
            message =  "设置锁屏壁纸成功"
        }
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    } catch (e: Exception) {
        Log.e("ImageViewerScreen", "Error setting wallpaper: ${e.message}", e)
        Toast.makeText(context, "设置壁纸失败，请重试", Toast.LENGTH_SHORT).show()
    }
}

private fun scaleBitmapToFitScreen(bitmap: Bitmap, screenWidth: Int, screenHeight: Int): Bitmap {
    val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat()
    val screenRatio = screenWidth.toFloat() / screenHeight.toFloat()

    val (newWidth, newHeight) = if (bitmapRatio > screenRatio) {
        // 图片更宽，以高度为准
        val height = screenHeight
        val width = (height * bitmapRatio).toInt()
        width to height
    } else {
        // 图片更高，以宽度为准
        val width = screenWidth
        val height = (width / bitmapRatio).toInt()
        width to height
    }
    return bitmap.scale(newWidth, newHeight)
}
private fun getScreenSizePx(context: Context): Pair<Int, Int> {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val bounds = wm.currentWindowMetrics.bounds
        // 这里可按需扣除系统栏 inset；多数锁屏用全屏 bounds 即可
        Pair(bounds.width(), bounds.height())
    } else {
        @Suppress("DEPRECATION")
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        @Suppress("DEPRECATION")
        val dm = DisplayMetrics().also { wm.defaultDisplay.getRealMetrics(it) }
        Pair(dm.widthPixels, dm.heightPixels)
    }
}

private fun createFitBitmap(
    src: Bitmap,
    targetW: Int,
    targetH: Int,
    backgroundColor: Int,
): Bitmap {
    val result = createBitmap(targetW, targetH)
    val canvas = Canvas(result)
    canvas.drawColor(backgroundColor)

    val srcRatio = src.width.toFloat() / src.height
    val dstRatio = targetW.toFloat() / targetH
    val scale = if (srcRatio > dstRatio) {
        targetW.toFloat() / src.width
    } else {
        targetH.toFloat() / src.height
    }

    val scaledW = (src.width * scale).toInt()
    val scaledH = (src.height * scale).toInt()
    val left = ((targetW - scaledW) / 2f)
    val top = ((targetH - scaledH) / 2f)

    val matrix = Matrix().apply {
        postScale(scale, scale)
        postTranslate(left, top)
    }
    canvas.drawBitmap(src, matrix, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
    return result
}

private fun createFillBitmap(
    src: Bitmap,
    targetW: Int,
    targetH: Int,
): Bitmap {
    val result = createBitmap(targetW, targetH)
    val canvas = Canvas(result)

    val scale = maxOf(
        targetW.toFloat() / src.width,
        targetH.toFloat() / src.height
    )
    val scaledW = src.width * scale
    val scaledH = src.height * scale
    val left = (targetW - scaledW) / 2f
    val top = (targetH - scaledH) / 2f

    val matrix = Matrix().apply {
        postScale(scale, scale)
        postTranslate(left, top)
    }
    canvas.drawBitmap(src, matrix, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
    return result
}

private fun createFillBitmap(
    src: Bitmap,
    targetW: Int,
    targetH: Int,
    gravity: CropGravity = CropGravity.CENTER
): Bitmap {
    val result = Bitmap.createBitmap(targetW, targetH, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(result)

    val scale = maxOf(targetW.toFloat() / src.width, targetH.toFloat() / src.height)
    val scaledW = src.width * scale
    val scaledH = src.height * scale

    val left = when {
        scaledW > targetW && gravity == CropGravity.LEFT -> 0f
        scaledW > targetW && gravity == CropGravity.RIGHT -> targetW - scaledW
        else -> (targetW - scaledW) / 2f
    }
    val top = when {
        scaledH > targetH && gravity == CropGravity.TOP -> 0f
        scaledH > targetH && gravity == CropGravity.BOTTOM -> targetH - scaledH
        else -> (targetH - scaledH) / 2f
    }

    val m = Matrix().apply {
        postScale(scale, scale)
        postTranslate(left, top)
    }
    canvas.drawBitmap(src, m, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
    return result
}


// 新增函数：创建裁剪填充的位图
private fun createCropFillBitmap(
    src: Bitmap,
    targetW: Int,
    targetH: Int
): Bitmap {
    val result = createBitmap(targetW, targetH)
    val canvas = Canvas(result)

    // 计算缩放比例，使用较大的缩放值以确保填满整个目标区域
    val scale = maxOf(
        targetW.toFloat() / src.width,
        targetH.toFloat() / src.height
    )

    // 按比例缩放后的尺寸
    val scaledW = src.width * scale
    val scaledH = src.height * scale

    // 计算偏移量，使图片居中裁剪
    val left = (targetW - scaledW) / 2f
    val top = (targetH - scaledH) / 2f

    val matrix = Matrix().apply {
        postScale(scale, scale)
        postTranslate(left, top)
    }

    canvas.drawBitmap(src, matrix, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
    return result
}
